问题描述(难度简单)
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
Example:
1 | int k = 3; |
Note:
You may assume that nums‘ length ≥ k-1 and k ≥ 1.
方法一:排序
维护一个k大小的数组,排序时间复杂度klogk,每次进入新元素判断当前k个有序数组中最小值,小于最小值不进入,大于最小值进入。整体时间复杂度nklogk。
方法一代码
1 | package FindKLargestNumber; |
方法二:优先队列
单纯排序的算法klogk的时间复杂度还有优化的空间,如果是最小堆的话搜素插入的时间只需要logk的复杂度,这里我们增加一个优先级队列的版本。优先级队列默认是一个堆的数据结构,堆这种数据结构是一个完全二叉树,满足每个子节点都要比父节点要小(小顶堆)或者大(大顶堆)。所以堆顶永远是k个数当中最小的,只需要比较堆顶的元素即可。同样的搜索插入的复杂度是logk。
方法二代码
1 | package FindKLargestNumber; |
总结
本质上两种方式都是维护一个k大小的数据结构,优先级队列在搜索插入的时间复杂度上具备优势,只需要logk的时间复杂度,优先级队列本质上是一个小顶堆。我们可以利用优先级队列去优化方法一。